package com.rc.saas.tenant.controller.operator;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.utils.DateHelper;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.model.channel.RcChannelApply;
import com.rc.saas.tenant.model.channel.RcChannelGainSetting;
import com.rc.saas.tenant.model.enterprise.EnterpriseMember;
import com.rc.saas.tenant.model.member.MemberInfo;
import com.rc.saas.tenant.model.member.RcMemberFlag;
import com.rc.saas.tenant.model.operator.RcOperator;
import com.rc.saas.tenant.model.tenant.TenantRole;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.search.tenant.TenantRoleSearch;
import com.rc.saas.tenant.service.enterprise.EnterpriseMemberService;
import com.rc.saas.tenant.service.operator.RcOperatorService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import com.rc.saas.tenant.vo.channel.RcChannelApplyVo;
import com.rc.saas.tenant.vo.elec.ElecCountVo;
import com.rc.saas.tenant.vo.operator.RcOperatorVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.List;

/**
 * 加盟商
 */
@Controller
@RequestMapping("/operator")
public class RcOperatorController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private String prefix = "/templates/operator";

    @Autowired
    private RcOperatorService operatorService;

    @Autowired
    private EnterpriseMemberService enterpriseMemberService;

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index() {
        return "/templates/operator/operator";
    }

    @ResponseBody
    @RequestMapping("/listPageOperator")
    public WebPageInfo listPageOperator(String operatorName, Integer pageNo, Integer pageSize) {
        PageInfo<RcOperatorVo> pageInfo = operatorService.listPageOperator(operatorName, pageNo, pageSize);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }

    /**
     * 导出加盟商列表
     */
    @ResponseBody
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public TResponse export(String operatorName,
                            @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
                            @RequestParam(value = "pageSize", defaultValue = "1000") Integer pageSize, HttpServletResponse response) {
        try {
            response.setHeader("Set-Cookie", "fileDownload=true; path=/");
            PageInfo<RcOperatorVo> pageInfo = operatorService.listPageOperator(operatorName, pageNo, pageSize);
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("加盟商列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), RcOperatorVo.class).sheet("加盟商列表").doWrite(pageInfo.getList());
            return null;
        } catch (Exception e) {
            logger.error("导出加盟商列表失败", e.getMessage());
            return TResponse.FAIL(e.getMessage());
        }
    }

    @ResponseBody
    @RequestMapping("/updateOperatorApplyForAudit")
    public TResponse updateChannelApplyForAudit(Long id, Long memberId, String status, String remark) {
        operatorService.updateOperatorApplyForAudit(id, memberId, status, remark);
        return TResponse.SUCCESS();
    }

    @RequestMapping("/add")
    public String add(Model model) {
        TenantUser user = ShiroUtils.getSessionUser();
        List<EnterpriseMember> list = enterpriseMemberService.selectEnterpriseMembers(user.getTenantCode());
        model.addAttribute("enterpriseList", list);
        return prefix + "/addOperator";
    }

    @RequestMapping("/edit/{id}")
    public String edit(Model model, @PathVariable("id") Long id) {
        RcOperator operator = operatorService.selectByPrimaryKey(id);
        model.addAttribute("operator", operator);
        TenantUser user = ShiroUtils.getSessionUser();
        List<EnterpriseMember> list = enterpriseMemberService.selectEnterpriseMembers(user.getTenantCode());
        model.addAttribute("enterpriseList", list);
        return prefix + "/editOperator";
    }

    @RequestMapping("/detail/{id}")
    public String detail(Model model, @PathVariable("id") Long id) {
        RcOperator operator = operatorService.selectByPrimaryKey(id);
        operator.setCreatedBy(DateHelper.dataToString(operator.getCreatedTime(), DateHelper.DATE_COMMON_FORMAT));
        model.addAttribute("operator", operator);
        ElecCountVo elecCountVo = operatorService.loadElecCount(id);
        model.addAttribute("elecCountVo", elecCountVo);

        TenantUser user = ShiroUtils.getSessionUser();
        EnterpriseMember enterpriseMemberInfo = enterpriseMemberService.selectByPrimaryKey(operator.getEnterpriseId());
        model.addAttribute("enterpriseMemberInfo", enterpriseMemberInfo);
        /*ist<EnterpriseMember> list = enterpriseMemberService.selectEnterpriseMembers(user.getTenantCode());
        model.addAttribute("enterpriseList", list);*/
        return prefix + "/detailOperator";
    }

    @ResponseBody
    @RequestMapping("/saveOperator")
    public TResponse saveOperator(RcOperator operator) {
        TenantUser user = ShiroUtils.getSessionUser();
        return operatorService.saveOperator(user.getTenantCode(), operator);
    }

    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public TResponse delChannelApply(Long id) {
        operatorService.deleteOperator(id);
        return TResponse.SUCCESS();
    }

    @ResponseBody
    @RequestMapping("/updateOperatorForInvoice")
    public TResponse updateOperatorForInvoice(Long id,
                                              String invoiceDateType,
                                              BigDecimal invoiceSingleMaxAmount,
                                              BigDecimal invoiceMaxAmount,
                                              Integer invoiceEachMaxGet,
                                              Integer invoiceMaxGet) {
        RcOperator operator = operatorService.selectByPrimaryKey(id);
        operator.setInvoiceDateType(invoiceDateType);
        operator.setInvoiceSingleMaxAmount(invoiceSingleMaxAmount);
        operator.setInvoiceMaxAmount(invoiceMaxAmount);
        operator.setInvoiceEachMaxGet(invoiceEachMaxGet);
        operator.setInvoiceMaxGet(invoiceMaxGet);
        operatorService.updateByPrimaryKeySelective(operator);
        return TResponse.SUCCESS();
    }


    @ResponseBody
    @RequestMapping("/addMember")
    public TResponse addMember(String mobile) {
        try {
            return operatorService.addMember(mobile);
        } catch (Exception e) {
            return TResponse.FAIL("审核失败");
        }

    }

}
